package ru.pb.game.objects.model;

import gnu.trove.impl.sync.TSynchronizedIntList;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntObjectHashMap;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import ru.pb.game.objects.model.enums.CHANNEL_TYPE;
import ru.pb.game.objects.model.players.Player;
import ru.pb.game.objects.model.room.Room;
import ru.pb.game.objects.storage.ObjectsStorage;

public class CHANNEL
{
	private int _id;
	private CHANNEL_TYPE _type;
	private String _announce;
	private TSynchronizedIntList _players;
	private TIntObjectHashMap<Room> _rooms = new TIntObjectHashMap<Room>();

	public CHANNEL(int id, CHANNEL_TYPE type, String announce)
	{
		_id = id;
		_type = type;
		_announce = announce;
		_players = new TSynchronizedIntList(new TIntArrayList(300));
	}

	/**
	 * @return Порядковый номер.
	 */
	public int getId()
	{
		return _id;
	}

	/**
	 * @return Номер типа.
	 */
	public int getType()
	{
		return _type.get();
	}

	/**
	 * @return Тип.
	 */
	public CHANNEL_TYPE getTypeEnum()
	{
		return _type;
	}

	/**
	 * @return Сообщение.
	 */
	public String getAnnounce()
	{
		return _announce;
	}

	/**
	 * @return Длинна сообщения.
	 */
	public int getAnnounceSize()
	{
		return _announce.length();
	}

	public void addPlayer(Player p)
	{
		_players.add(p.getObjectId());
	}

	public void removePlayer(Player p)
	{
		int idToRemove = p.getObjectId();
		TIntIterator players = _players.iterator();
		while(players.hasNext())
		{
			int plId = players.next();
			if(idToRemove == plId)
				players.remove();
		}
	}

	public TSynchronizedIntList getAllPlayers()
	{
		return _players;
	}

	public List<Player> getWaitPlayers()
	{
		List<Player> temp = new ArrayList<Player>();
		for(int id : _players.toArray())
		{
			Player p = ObjectsStorage.getInstance().getPlayer(id);
			if(p.getRoom() == null)
				temp.add(p);
		}
		return temp;
	}

	public void addRoom(Room r)
	{
		_rooms.put(r.getRoomId(), r);
	}

	public void removeEmptyRooms()
	{
		Iterator<Room> rooms = _rooms.valueCollection().iterator();
		while(rooms.hasNext())
		{
			Room r = rooms.next();
			if(r.getAllPlayers().isEmpty())
			{
				rooms.remove();
			}
		}
	}

	public Room getRoom(int index)
	{
		return _rooms.get(index);
	}

	public Collection<Room> getRooms()
	{
		return _rooms.valueCollection();
	}
}